package com.rfsp.common.shiro;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rfsp.common.mapper.UserMapper;
import com.rfsp.common.pojo.po.UserPO;


/**
 * shiro登录验证及权限管理
 * @author 李阳
 *
 */

@Component
public class ShiroRealm extends SimpleAccountRealm {
	private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

	@Autowired
	private UserMapper userMapper;

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		logger.info("-----------------doGetAuthenticationInfo----------------------");
		// 获取用户填写token
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userCode", token.getUsername());
//		map.put("userLevel", ShiroUtils.getAttribute("userLevel"));
		UserPO user = userMapper.getUserByUserCode(token.getUsername());
		// 返回shiro后台验证登录
		return new SimpleAuthenticationInfo(token.getUsername(), user.getPassword(), getName());
	}
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("-----------------doGetAuthorizationInfo----------------------");
		
		Set<String> permsSet = ShiroUtils.getAttribute("userPerms");
		Set<String> rolesSet = ShiroUtils.getAttribute("role");
		/* 这里编写授权代码 */// 创建当前用户角色
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(rolesSet);
		permsSet.remove(null);
		info.setRoles(rolesSet);
		info.setStringPermissions(permsSet);
		return info;
	}



}
